package pers.lan.print.poi;

import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import org.junit.Test;
import pers.lan.print.ZXing;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * @author <a href="mailto:1728209643@qq.com">lan</a>
 * @class pers.lan.print.poi.POITest
 * @date 2019-04-11 13:53
 */
public class POITest {

    private final static String srcDest = "/Users/lan/Desktop/mb.xls";
    private final static String outDest = "/Users/lan/Desktop/out.xls";
    private final static String img = "/Users/lan/Desktop/p.jpg";
    private final static String ouyImg = "/Users/lan/Desktop/d.jpg";


    @Test
    public void test1() throws Exception {
        Workbook workbook = new HSSFWorkbook(new FileInputStream(srcDest));
        Sheet sheet = workbook.getSheetAt(0);
        int lastRowNum = sheet.getLastRowNum();
        System.out.println(lastRowNum);

        OutputStream out = new FileOutputStream(ouyImg);
        ZXing.encode("asdhajd", out);
        out.close();
        InputStream in = new FileInputStream(ouyImg);
        byte[] bytes = IOUtils.toByteArray(in);
        int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
        in.close();

        CreationHelper helper = workbook.getCreationHelper();
        Drawing<?> drawing = sheet.createDrawingPatriarch();
        for (int i = 1; i < lastRowNum + 1; i++) {
            Row row = sheet.getRow(i);
            short lastCellNum = row.getLastCellNum();
            System.out.print("row " + i + ": ");
            for (int j = 0; j < lastCellNum; j++) {
                Cell cell = row.getCell(j);
                cell.setCellValue("");
                System.out.print(j + "#" + cell.getStringCellValue() + "\t");
                if (j % 2 == 0) {
                    ClientAnchor anchor = helper.createClientAnchor();
                    anchor.setRow1(i);
//                    anchor.setRow2(i);
                    anchor.setCol1(j);
                    anchor.setDx1(180);
                    anchor.setDy1(20);

//                    anchor.setCol2(j);
//                    anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_AND_RESIZE);
                    Picture picture = drawing.createPicture(anchor, pictureIdx);
                    picture.resize();
                }
            }
            System.out.println();
        }
        workbook.setPrintArea(0, 0, 6, 0, lastRowNum);

        workbook.write(new FileOutputStream(outDest));
        workbook.close();

//        Printer.print(outDest, new HashMap<>());

    }

    @Test
    public void testZX() throws Exception {
    }
}
